import 'dart:async';
import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import '../../manager/ywx_manager.dart';
import '../bean/worksdo/equipment_management_bean.dart';
import '../bean/worksdo/equipment_management_bean.dart';
import '../bean/worksdo/hardware_collar_bean.dart';
import '../bean/worksdo/hardware_return_bean.dart';
import '../bean/worksdo/material_requisition_bean.dart';
import '../bean/wroks/dispatchingaudit_bean.dart';

///设备管理：我的工单：工单领用：五金退库
class HardwareReturnModel {
  ///根据维修工单号获取五金信息
  static Future<
          AppHttpResult<List<HardwareReturnListBean>, HardwareReturnListBean>>
      GetMaterialPickingByRepairOrderId(BuildContext context, bool isEnableLoad,
          {ResponseCallbackWithStringCode_? onError = null,
          String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer = new Completer<
        AppHttpResult<List<HardwareReturnListBean>, HardwareReturnListBean>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] =
        "GetMaterialPickingByRepairOrderId"; //根据维修工单号获取五金信息
    var FactoryId = AppDataConfig.getFactory()?.FactoryId; //工厂id
    var RepairOrderId = searchInfo?.equipmentInfo?.Id;
    // print("工单号：${searchInfo?.equipmentInfo?.RepairNo}工单id：$RepairOrderId");
    var Status = searchInfo?.ReceivingStatusKey;
    if (StringUtils.isEmpty(Status)) {
      Status = "-1"; //全部
    }
    var data =
        "{RepairOrderId:$RepairOrderId, PageIndex:$PageNo, PageSize:$PageSize, Status:$Status }";
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('五金领用记录列表数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<
              AppHttpResult<List<HardwareReturnListBean>,
                  HardwareReturnListBean>>(AppHttpResult()
            ..Data = <HardwareReturnListBean>[]
            ..t2 = HardwareReturnListBean())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<
        AppHttpResult<List<HardwareReturnListBean>, HardwareReturnListBean>>;
  }

  ///根据维修工单号获取五金信息(详情)
  static Future<AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>
      GetMaterialPickingListByMaterialPickingId(BuildContext context,
          HardwareReturnListBean? hardwareReturnListBean, bool isEnableLoad,
          {ResponseCallbackWithStringCode_? onError = null,
          String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer = new Completer<
        AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] =
        "GetMaterialPickingListByMaterialPickingId"; //根据维修工单号获取五金信息(详情信息)
    // var FactoryId = AppDataConfig.getFactory()?.FactoryId; //工厂id
    // var RepairOrderId = searchInfo?.equipmentInfo?.Id;
    // print("工单号：${searchInfo?.equipmentInfo?.RepairNo}工单id：$RepairOrderId");
    // var Status = searchInfo?.ReceivingStatusKey;
    // if (StringUtils.isEmpty(Status)) {
    //   Status = "-1"; //全部
    // }
    // var data =
    //     "{RepairOrderId:$RepairOrderId, PageIndex:$PageNo, PageSize:$PageSize, Status:$Status }";
    queryParameters['data'] = hardwareReturnListBean?.PickId ?? "";
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('五金详情信息返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>(
              AppHttpResult()
                ..Data = <HardwareReturnBean>[]
                ..t2 = HardwareReturnBean())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>;
  }

  ///五金退库
  ///isReturnAll 是否整架退库
  static Future<AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>
      MaterialPickingReturn(BuildContext context,bool isReturnAll,
          HardwareReturnSubData? mSubData, bool isEnableLoad,
          {ResponseCallbackWithStringCode_? onError = null,
          String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer = new Completer<
        AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>();
    var url = Url.baseurl() + Url.repairOrder;
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    //var isReturnAll = mSubData?.hardwareReturnListBean?.isReturnAll() ?? false;
    if (isReturnAll) {
      //整单退
      queryParameters['type'] = "MaterialPickingReturn"; //五金领用整单退回
      queryParameters['data'] =
          mSubData?.hardwareReturnListBean?.PickId ?? ""; //五金领用id
    } else {
      //单个退;fixme 不用做申请数量的验证，服务器已经做了验证。
      queryParameters['type'] = "MaterialPickingListReturn"; //五金领用单个退回
      var json = mSubData?.jsonEncodeToJson();
      // 五金单个退库数据：{"FactoryId":"1","BackNum":"0,1","BodyId":"1961,1962"}
      // print("五金单个退库数据：$json");
      queryParameters['data'] = json;
    }
    // return Future.value(null);
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('五金详情信息返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>(
              AppHttpResult()
                ..Data = <HardwareReturnBean>[]
                ..t2 = HardwareReturnBean())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<HardwareReturnBean>, HardwareReturnBean>>;
  }
}
